package com.lzj.myvideo.service.impl;

import com.lzj.myvideo.common.MD5Util;
import com.lzj.myvideo.common.ServerResponse;
import com.lzj.myvideo.service.UserService;
import com.shortvideo.dao.follow_fansMapper;
import com.shortvideo.dao.userMapper;
import com.shortvideo.pojo.User;
import com.shortvideo.pojo.follow_fans;
import com.shortvideo.pojo.follow_fansExample;
import com.shortvideo.pojo.userExample;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import static com.lzj.myvideo.common.Const.pathConstant.*;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private userMapper userMapper;

    @Autowired
    private follow_fansMapper follow_fansMapper;

    //最终全路径
    String finalVideoPath = "";



    private void updateUserInfo(User user) {
        if (user != null) {
            userExample userExample = new userExample();
            com.shortvideo.pojo.userExample.Criteria criteria = userExample.createCriteria();
            criteria.andIdEqualTo(user.getId());
            userMapper.updateByExampleSelective(user, userExample);
        }
    }


    /**
     * 检查用户是否存在 存在返回true
     * @param username
     * @return
     */
    @Override
    public boolean checkUsernameIsExit(String username) {
        int i = userMapper.selectOne(username);
        if (i == 1)
            return true;
        else
            return false;
    }

    @Override
    public int saveUser(User user) {
        return userMapper.insert(user);
    }

    @Override
    public User findUser(User user) {
        userExample userExample = new userExample();
        com.shortvideo.pojo.userExample.Criteria criteria = userExample.createCriteria();
        criteria.andUsernameEqualTo(user.getUsername());
        criteria.andPasswordEqualTo(MD5Util.encryptPassword(user.getPassword()));
        User user1 = userMapper.selectByExample(userExample);
        return user1;
    }

    @Override
    public User queryUser(String userId) {
        userExample userExample = new userExample();
        com.shortvideo.pojo.userExample.Criteria criteria = userExample.createCriteria();
        criteria.andIdEqualTo(userId);
        User user = userMapper.selectByExample(userExample);
        user.setPassword(null);
        return user;
    }

    /**
     * 上传头像
     * @param userId
     * @param files
     * @return
     */
    @Override
    public ServerResponse userFaceUpload(String userId, MultipartFile[] files) {
        String DBpath = USER_INFO + userId;
        FileOutputStream fileOutputStream = null;
        InputStream inputStream = null;
        try {
            if (files[0] != null) {
                String filename = files[0].getOriginalFilename();
                finalVideoPath = DISK_PATH  + DBpath + "/" +filename;
                DBpath += ("/"+filename);
                File faceFile = new File(finalVideoPath);
                if (faceFile.getParentFile() != null || faceFile.getParentFile().isDirectory() ){
                    faceFile.getParentFile().mkdirs();
                }
                fileOutputStream = new FileOutputStream(faceFile);
                inputStream = files[0].getInputStream();
                IOUtils.copy(inputStream,fileOutputStream);
            }else{
                return ServerResponse.createByError("文件为空");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fileOutputStream!= null){
                try {
                    fileOutputStream.flush();
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        User user = new User();
        user.setId(userId);
        user.setU_face_image_path(DBpath);
        this.updateUserInfo(user);
        return ServerResponse.createBySuccess(DBpath);
    }

    /**
     * 上传背景图
     * @param userId
     * @param files
     * @return
     */
    @Override
    public ServerResponse userBackgroundUpload(String userId, MultipartFile[] files) {
        String DBpath = USER_INFO + userId;
        FileOutputStream fileOutputStream = null;
        InputStream inputStream = null;
        try {
            if (files[0] != null) {
                String filename = files[0].getOriginalFilename();
                finalVideoPath = DISK_PATH  + DBpath + "/" +filename;
                DBpath += ("/"+filename);
                File faceFile = new File(finalVideoPath);
                if (faceFile.getParentFile() != null || faceFile.getParentFile().isDirectory() ){
                    faceFile.getParentFile().mkdirs();
                }
                fileOutputStream = new FileOutputStream(faceFile);
                inputStream = files[0].getInputStream();
                IOUtils.copy(inputStream,fileOutputStream);
            }else{
                return ServerResponse.createByError("文件为空");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fileOutputStream!= null){
                try {
                    fileOutputStream.flush();
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        User user = new User();
        user.setId(userId);
        user.setU_background_path(DBpath);
        this.updateUserInfo(user);
        return ServerResponse.createBySuccess(DBpath);
    }

    /**
     * 用户关注业务
     * @param userId
     * @param followId
     * @return
     */
    @Override
    @Transactional
    public ServerResponse follow(String userId, String followId) {
        follow_fans follow_fans = new follow_fans();
        follow_fans.setFans_id(userId);
        follow_fans.setFollow_id(followId);
        int result1 = follow_fansMapper.insert(follow_fans);
        if (result1 < 1 ){
            throw new RuntimeException("数据库插入异常");
        }
        //增加该用户的关注数
        int result2 = userMapper.increaseFansFollowCount(userId);
        if (result2 < 1 ){
            throw new RuntimeException("数据库插入异常");
        }
        //增加被关注着的粉丝数
        int result3 = userMapper.increaseFollowFansCount(followId);
        if (result3 < 1 ){
            throw new RuntimeException("数据库插入异常");
        }

        return ServerResponse.createBySuccess();
    }

    /**
     * 用户取消关注业务
     * @param userId
     * @param followId
     * @return
     */
    @Override
    @Transactional
    public ServerResponse unfollow(String userId, String followId) {
        follow_fansExample follow_fansExample = new follow_fansExample();
        com.shortvideo.pojo.follow_fansExample.Criteria criteria = follow_fansExample.createCriteria();
        criteria.andFan_idEqualTo(userId);
        criteria.andFollow_idEqualTo(followId);
        int result1 = follow_fansMapper.deleteByExample(follow_fansExample);
        if (result1 < 1 ){
            throw new RuntimeException("数据库插入异常");
        }
        //增加该用户的关注数
        int result2 = userMapper.reductionFansFollowCount(userId);
        if (result2 < 1 ){
            throw new RuntimeException("数据库插入异常");
        }
        //增加被关注着的粉丝数
        int result3 = userMapper.reductionFollowFansCount(followId);
        if (result3 < 1 ){
            throw new RuntimeException("数据库插入异常");
        }

        return ServerResponse.createBySuccess();
    }

    @Override
    public Boolean isFollow(String userId, String followId) {
        follow_fansExample follow_fansExample = new follow_fansExample();
        com.shortvideo.pojo.follow_fansExample.Criteria criteria = follow_fansExample.createCriteria();
        criteria.andFan_idEqualTo(userId);
        criteria.andFollow_idEqualTo(followId);
        follow_fans follow_fans = follow_fansMapper.selectByExample(follow_fansExample);
        if (follow_fans!=null){
            return true;
        }else {
            return false;
        }
    }


}
